package com.ctshk.rpc.system.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ctshk.common.enums.*;
import com.ctshk.common.model.TokenUser;
import com.ctshk.rpc.system.entity.SysSupplier;
import com.ctshk.rpc.system.service.ISysPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.QueryAgentByNameDTO;
import com.ctshk.rpc.system.dto.SysAgentDTO;
import com.ctshk.rpc.system.dto.SysAgentQueryListDTO;
import com.ctshk.rpc.system.dto.SysAgentUsableDTO;
import com.ctshk.rpc.system.entity.SysAgent;
import com.ctshk.rpc.system.mapper.SysAgentMapper;
import com.ctshk.rpc.system.req.SysAddAgentReq;
import com.ctshk.rpc.system.req.SysAgentApprovalReq;
import com.ctshk.rpc.system.req.SysAgentQueryListReq;
import com.ctshk.rpc.system.req.SysAgentQueryUsableListReq;
import com.ctshk.rpc.system.req.SysAgentUpdateStatusReq;
import com.ctshk.rpc.system.service.ISysAgentService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;

/**
 * <p>
 * 代理商 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-04
 */
@DubboService
public class SysAgentServiceImpl extends ServiceImpl<SysAgentMapper, SysAgent> implements ISysAgentService, BaseService {


    @Autowired
    private SysAgentMapper sysAgentMapper;

    @Autowired
    private SysPermissionServiceImpl sysPermissionService;

    @DubboReference
    private ISysApprovalService sysApprovalService;


    /**
     * 新增代理商
     *
     * @param sysAddAgentReq 入参
     * @param userId         当前登录人id
     * @param addType        1仅保存,2走审批流程
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(SysAddAgentReq sysAddAgentReq, Long userId, int addType) {
        // 查重代理商中英文名
        QueryWrapper<SysAgent> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysAgent::getEnName, sysAddAgentReq.getEnName()).or();
        queryWrapper.lambda().eq(SysAgent::getCnName, sysAddAgentReq.getCnName());
        List<SysAgent> agents = sysAgentMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(agents)) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6003);
        }
        // 查重系统编码
        QueryWrapper<SysAgent> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.lambda().eq(SysAgent::getFinanceSysCode, sysAddAgentReq.getFinanceSysCode());
        if (CollectionUtils.isNotEmpty(sysAgentMapper.selectList(codeQueryWrapper))) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6005);
        }

        SysAgent sysAgent = EntityUtil.copy(sysAddAgentReq, SysAgent.class);
        sysAgent.setCreateId(userId);
        long nextId = SnowflakeIdWorker.nextId();
        sysAgent.setId(nextId);
        sysAgent.setGmtCreate(LocalDateTime.now());


        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDAGENT_SYSTEM.getCode(), nextId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            sysAgent.setCheckStatus(AgentCheckStatus.REVIEW.getCode());
            sysAgent.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            sysAgent.setCheckStatus(AgentCheckStatus.SAVED.getCode());
            sysAgent.setStatus(SupplierStatus.DISABLE.getCode());
        }


        sysAgentMapper.insert(sysAgent);
        return Result.success();
    }

    /**
     * 根据id查询代理商详情
     *
     * @param id 代理商id
     * @return
     */
    @Override
    public Result<SysAgentDTO> query(Long id) {
        SysAgent sysAgent = sysAgentMapper.selectById(id);
        if (null != sysAgent) {
            SysAgentDTO sysAgentDTO = EntityUtil.copy(sysAgent, SysAgentDTO.class);
            return Result.success(sysAgentDTO);
        }
        return Result.failed(SystemError.SYS_411);
    }

    /**
     * 编辑代理商
     *
     * @param userId
     * @param addType 1仅保存,2走审批流程
     * @return
     */
    @Override
    public Result editAgent(SysAddAgentReq req, Long userId, int addType) {

        Long agentId = req.getId();
        SysAgent oldSysAgent = sysAgentMapper.selectById(agentId);
        String newCnName = req.getCnName();
        String newEnName = req.getEnName();
        if (!newCnName.equals(oldSysAgent.getCnName()) || !newEnName.equals(oldSysAgent.getEnName())) {
            // 查重中英文名
            QueryWrapper<SysAgent> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .and(e->e.eq(SysAgent::getCnName, newCnName)
                            .or().eq(SysAgent::getEnName, newEnName))
                    .ne(SysAgent::getId, agentId);
            if (CollectionUtils.isNotEmpty(baseMapper.selectList(queryWrapper))) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6003);
            }
        }


        SysAgent newSysAgent = EntityUtil.copy(req, SysAgent.class);
        newSysAgent.setGmtModified(LocalDateTime.now());
        newSysAgent.setModifiedId(userId);


        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDAGENT_SYSTEM.getCode(), agentId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            newSysAgent.setCheckStatus(AgentCheckStatus.REVIEW.getCode());
            newSysAgent.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            newSysAgent.setCheckStatus(AgentCheckStatus.SAVED.getCode());
            newSysAgent.setStatus(SupplierStatus.DISABLE.getCode());
        }
        int update = sysAgentMapper.updateById(newSysAgent);
        if (0 == update) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(agentId);

    }

    /**
     * 代理商管理列表查询
     *
     * @param req 入参
     * @return
     */
    @Override
    public PageResponse<SysAgentQueryListDTO> queryAgentList(SysAgentQueryListReq req, TokenUser tokenUser) {
        IPage<SysAgentQueryListDTO> agentPage = new Page<>(req.getPageNo(), req.getPageSize());
        agentPage = sysAgentMapper.queryAgentList(req, agentPage);
        return new PageResponse<>(agentPage.getRecords(), agentPage.getCurrent() == 1,
                agentPage.getTotal() <= (agentPage.getCurrent() * agentPage.getSize()),
                agentPage.getTotal(), agentPage.getCurrent(), agentPage.getSize());
    }

    /**
     * 代理商管理列表查询（验证）
     *
     * @param req 入参
     * @return
     */
    @Override
    public PageResponse<SysAgentQueryListDTO> queryAgentListPer(SysAgentQueryListReq req, TokenUser tokenUser) {
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            req.setIsNotAdmin(1);
            req.setUserIds(permissionResult.getData());
        }
        IPage<SysAgentQueryListDTO> agentPage = new Page<>(req.getPageNo(), req.getPageSize());
        agentPage = sysAgentMapper.queryAgentList(req, agentPage);
        return new PageResponse<>(agentPage.getRecords(), agentPage.getCurrent() == 1,
                agentPage.getTotal() <= (agentPage.getCurrent() * agentPage.getSize()),
                agentPage.getTotal(), agentPage.getCurrent(), agentPage.getSize());
    }

    /**
     * 代理商管理列表查询
     *
     * @param req 入参
     * @return
     */
    @Override
    public PageResponse<SysAgentQueryListDTO> queryAgentListAll(SysAgentQueryListReq req) {
        IPage<SysAgentQueryListDTO> agentPage = new Page<>(req.getPageNo(), req.getPageSize());
        agentPage = sysAgentMapper.queryAgentList(req, agentPage);
        return new PageResponse<>(agentPage.getRecords(), agentPage.getCurrent() == 1,
                agentPage.getTotal() <= (agentPage.getCurrent() * agentPage.getSize()),
                agentPage.getTotal(), agentPage.getCurrent(), agentPage.getSize());
    }

    /**
     * 通过名称查询代理商
     *
     * @param name 代理商名称
     * @return
     */
    @Override
    public Result<List<QueryAgentByNameDTO>> queryAgentByName(String name) {
        QueryWrapper<SysAgent> queryWrappe = new QueryWrapper<>();
        queryWrappe.lambda().like(SysAgent::getCnName, name);
        queryWrappe.lambda().eq(SysAgent::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SysAgent> list = sysAgentMapper.selectList(queryWrappe);
        List<QueryAgentByNameDTO> nameList = EntityUtil.copyList(list, QueryAgentByNameDTO.class);
        return Result.success(nameList);
    }

    @Override
    public Result updateStatus(SysAgentUpdateStatusReq req) {
        SysAgent sysAgent = baseMapper.selectById(req.getId());
        if (sysAgent == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        //如果改为有效状态
        if (req.getNewStatus() == SupplierStatus.ENABLE.getCode()) {
            //审批状态不是审批通过的其他状态下不能修改为有效状态
            if (sysAgent.getCheckStatus() != AgentCheckStatus.REVIEW_YES.getCode()) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6006);
            }
        }

        sysAgent.setStatus(req.getNewStatus());
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        sysAgent.setModifiedId(req.getUserId());
        sysAgent.setGmtModified(nowLocalDateTime);
        baseMapper.updateById(sysAgent);
        return Result.success();
    }

    @Override
    public Result approval(SysAgentApprovalReq req) {


        if (req.getApprovalId() == null) {
            return Result.failed(SystemError.SYS_402);
        }
        if (!ApprovalStatus.isCheckStatus(req.getApprovalStatus())) {
            return Result.failed(SystemError.SYS_402);
        }

        QueryWrapper<SysAgent> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysAgent::getId, req.getBusinessId());
        queryWrapper.lambda().eq(SysAgent::getIsDeleted, IsDeletedCode.NO);
        SysAgent agent = baseMapper.selectOne(queryWrapper);
        if (agent == null) {
            return Result.failed(SystemError.SYS_411);
        }

        /**
         * 审批
         */
        Result<ApprovalCheckDTO> result = sysApprovalService.check(req.getApprovalId(), req.getUserId(),
                req.getApprovalStatus(), req.getRemark());
        if (!result.isSuccess()) {
            SystemError systemError = SystemError.getDefined(result.getCode());
            return Result.failed(systemError);
        }
        if (result.getData() == null || !result.getData().getIsFinish()) {
            return Result.success();
        }

        //审批状态（0：撤回，4：审批不通过，3：审批通过）
        if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_YES.getCode()) {
            //审批通过
            agent.setCheckStatus(SupplierAddCheckStatus.REVIEW_YES.getCode());
            agent.setStatus(SupplierStatus.ENABLE.getCode());

        } else if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_NO.getCode()) {
            //审批不通过
            agent.setCheckStatus(SupplierAddCheckStatus.REVIEW_NO.getCode());
            agent.setStatus(SupplierStatus.DISABLE.getCode());
        } else {
            //撤回
            agent.setCheckStatus(SupplierAddCheckStatus.SAVED.getCode());//已保存
            agent.setStatus(SupplierStatus.DISABLE.getCode());
        }


        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        agent.setModifiedId(req.getUserId());
        agent.setGmtModified(nowLocalDateTime);
        baseMapper.updateById(agent);
        return Result.success();


    }

    /**
     * 查询可用的代理商列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<List<SysAgentUsableDTO>> queryUsableAgentList(SysAgentQueryUsableListReq req) {
        List<SysAgentUsableDTO> list = sysAgentMapper.queryUsableAgentList(req);
        return newResult(list);
    }

    @Override
    public Result<List<QueryAgentByNameDTO>> queryAgentByNameAndIds(String name, List<Long> ids) {
        List<QueryAgentByNameDTO> nameList = sysAgentMapper.queryAgentByNameAndIds(name, StringUtils.join(ids, ","));
        return Result.success(nameList);
    }

    @Override
    public Result deleteById(Long id) {
        return baseMapper.deleteById(id) > 0 ? Result.success() : Result.failed(SystemError.CMS_23001);
    }
}

